import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

//应用初始状态
const state = {
    count: 10,
    todes:[
      { id: 1, text: '11...11', done: true },
      { id: 2, text: '22...22', done: false }
    ]
};
//计算属性
//返回值会根据它的依赖被缓存起来，
//且只有当它的依赖值发生了改变才会被重新计算
const getters={
  to_count:state=>{
    return state.count;
  },
  get_count:(state,getters,rootState, rootGetters)=>{
    return getters.to_count + '###';
  },
  getTodoById:(state)=>(id)=>{
    return state.todes.find(todo=>todo.id==id);
  }
};
//更改Vuex的store中的状态
//必须同步执行
const mutations = {
    add_count(state,n){
      console.log('s------',state);
      state.count+=n;
    },
    remove_count(state,n){
      state.count-=n;
    }
};
//提交的是mutation,而不是直接变更状态
//可以包含任意异步操作
const actions={
  add_countAsync({dispatch, commit, getters, rootGetters},v){
    console.log(v)
    return new Promise((resolve,reject)=>{
      setTimeout(()=>{
        commit('add_count',v.num);
        dispatch('add_countAsync',v.num,{root:true});
        resolve()
      },1000);
      reject()
    });
  }
  // async actionA({commit}){
  //   commit('gotData',await gotData())
  // },
  // async actionB({dispatch, commit}){
  //   await dispatch('actionA')
  //   commit('gotOtherData',await gotOtherData())
  // }
};

const moduleA={
  state:state,
  mutations:mutations,
  actions:actions,
  getters:getters
}

//创建store实例
export default new Vuex.Store({
    state:{
      count:1000,
    },
    actions:{
      add_countAsync({ dispatch, commit, getters, rootGetters },v){
        console.log('root',v)
      },
    },
    modules:{
      a:{
        namespaced:true,
        ...moduleA
      }
    }
});
